/*
 * @Author: zgz
 * @Date: 2019-10-11 14:58:58
 * @LastEditTime: 2020-04-14 14:51:59
 * @LastEditors: zgz
 * @Description: file conten
 */
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
// import { UploadXHRArgs, UploadFile, NzMessageService } from 'ng-zorro-antd';
import COS from 'cos-js-sdk-v5';
import { UtilsService } from '../../services/utils/utils.service';
import { environment } from '../../../../environments/environment';
import { Observable, Observer } from 'rxjs';

@Component({
    selector: 'cos-upload',
    templateUrl: './cos-upload.component.html',
    styleUrls: ['./cos-upload.component.scss']
})

export class CosUploadComponent implements OnInit {

    @Input() maxFileNumber: any;
    @Input() defaultImg: any;
    @Input() activeItem: any;//数组渲染多次调用组件用到
    @Input() setNamed: boolean = false;
    @Input() mkdir: string = "";
    @Output() callback = new EventEmitter();
    @Output() removecallback = new EventEmitter();

    cos = new COS({
        SecretId: environment.SecretId,
        SecretKey: environment.SecretKey
    })

    showUploadList = {
        showPreviewIcon: true,
        showRemoveIcon: true,
        hidePreviewIconInNonImage: true
    };
    fileList: any = [];
    previewImage: string | undefined = '';
    previewVisible = false;

    constructor(
        // private msg: NzMessageService,
        private util: UtilsService
    ) { }

    ngOnInit() {

        if (this.defaultImg) {

            if (typeof this.defaultImg === "string") {
                this.defaultImg = { "url": this.defaultImg };
            }

            if (this.util.isArray(this.defaultImg)) {
                this.fileList = this.defaultImg
            } else {
                this.fileList.push(this.defaultImg);
            }
        } else {
            this.defaultImg = { "url": "" };
        }
    }

    remove = (file: any) => {
        if (this.activeItem || this.activeItem == 0) {
            this.removecallback.emit({ file: file, item: this.activeItem });
        } else {
            this.removecallback.emit(file);
        }
        return true;
    }

    //限制图片只能上传png
    beforeUpload:any = (file: File) => {
        return new Observable((observer: Observer<boolean>) => {
            const isPng = file.type === 'image/png';
            if (!isPng) {
                // this.msg.error('只能上传PNG格式的图片!');
                observer.complete();
                return;
            }

            observer.next(isPng);
        });
    };

    handlePreview = (file: any) => {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
        console.log(file);

    };

    customRequest:any = (item: any) => {

        let file = item.file;

        let fileName: any;

        //是否需要固定命名
        if (this.setNamed && this.defaultImg.url) {
            fileName = this.defaultImg.url.split("doctor/")[1].split(".")[0] + '.' + file.name.split('.').pop();
        } else {
            fileName = this.util.random_string(30) + '.' + file.name.split('.').pop();
        }

        this.cos.putObject({
            Bucket: environment.Bucket,
            Region: environment.CosRegion,
            Key: this.mkdir + fileName,
            Body: file,
            onProgress: (event) => {
                if (event.total > 0) {
                    (event as any).percent = Math.round(event.loaded * 100 / event.total);
                }
                item.onProgress(event, item.file);
            }
        }, (err, data) => {


            if (data.statusCode == 200) {


                if (this.activeItem || this.activeItem == 0) {
                    this.callback.emit({ url: environment.resourceUrl + this.mkdir + fileName, item: this.activeItem });
                } else {
                    this.callback.emit(environment.resourceUrl + this.mkdir + fileName);
                }

                item.onSuccess(data, item.file, data);

            }

        });


    }





}
